/* Copyright (c) 2010-2020 Vadim Surov.
 */
package com.srv.client.widget;

import java.util.LinkedList;
import java.util.List;

import com.sencha.gxt.dnd.core.client.DndDropEvent;
import com.sencha.gxt.dnd.core.client.DropTarget;
import com.sencha.gxt.dnd.core.client.DND.Feedback;
import com.sencha.gxt.dnd.core.client.DND.Operation;
import com.sencha.gxt.widget.core.client.TabItemConfig;
import com.sencha.gxt.widget.core.client.TabPanel;
import com.srv.shared.Card;
import com.srv.shared.SetInfo;

public class SetTabPanel extends TabPanel implements SetView {

	private boolean isSafeToClose = true;

	/**
	 * @param model
	 *          the model to which the Ui will bind itself
	 */
	public SetTabPanel(final SetInfo setInfo, List<Card> cards) {
		super();
		setCards(cards);

		new DropTarget(this) {
			{
				setGroup("movecard");
				setFeedback(Feedback.INSERT);
				setOperation(Operation.COPY);
				setAllowSelfAsSource(true); 
			}
			@Override  
			protected void onDragDrop(DndDropEvent event) {  
				super.onDragDrop(event);  
				final List<?> dropcards = (List<?>)event.getData();
				final Card card = ((Card)dropcards.get(0)).copy();
				final CardPanel cardPanel = new CardPanel(card);

				final CardPanel activeCardPanel = (CardPanel) SetTabPanel.this.getActiveWidget();
				final int i = SetTabPanel.this.getWidgetIndex(activeCardPanel);

				insert(cardPanel, i, new TabItemConfig("*"+i, false));

				setActiveWidget(cardPanel);
			}			
		};				
	}

	private void setCards(List<Card> cards) {
		int i=0;
		for (Card card : cards) {
			add(new CardPanel(card), new TabItemConfig(""+i, false));
			++i;
		}		
	}

	@Override
	public boolean isSafeToClose() {
		return isSafeToClose;
	}

	@Override
	public List<Card> getCards() {
		final List<Card> cards = new LinkedList<Card>();
		for (int i=0, len = getWidgetCount(); i<len; ++i) {
			final CardPanel cardPanel = (CardPanel)getWidget(i); 
			cards.add(cardPanel.getCard());
		}
		return cards;
	}
}	

